﻿using System;
using System.Collections.Generic;
using GeoAPI.Geometries;

namespace YJKGridTopologyCal.Geometries
{
	public class CoordinateSequenceComparator : IComparer<ICoordinateSequence>
	{
		public static int Compare(double a, double b)
		{
			if (a < b)
			{
				return -1;
			}
			if (a > b)
			{
				return 1;
			}
			if (double.IsNaN(a))
			{
				if (double.IsNaN(b))
				{
					return 0;
				}
				return -1;
			}
			else
			{
				if (double.IsNaN(b))
				{
					return 1;
				}
				return 0;
			}
		}

		public CoordinateSequenceComparator()
		{
			this.DimensionLimit = int.MaxValue;
		}

		public CoordinateSequenceComparator(int dimensionLimit)
		{
			this.DimensionLimit = dimensionLimit;
		}

		public int Compare(object o1, object o2)
		{
			ICoordinateSequence s = (ICoordinateSequence)o1;
			ICoordinateSequence s2 = (ICoordinateSequence)o2;
			return this.Compare(s, s2);
		}

		protected int CompareCoordinate(ICoordinateSequence s1, ICoordinateSequence s2, int i, int dimension)
		{
			for (int j = 0; j < dimension; j++)
			{
				double ordinate = s1.GetOrdinate(i, (Ordinate)j);
				double ordinate2 = s2.GetOrdinate(i, (Ordinate)j);
				int num = CoordinateSequenceComparator.Compare(ordinate, ordinate2);
				if (num != 0)
				{
					return num;
				}
			}
			return 0;
		}

		public int Compare(ICoordinateSequence s1, ICoordinateSequence s2)
		{
			int count = s1.Count;
			int count2 = s2.Count;
			int dimension = s1.Dimension;
			int dimension2 = s2.Dimension;
			int num = dimension;
			if (dimension2 < num)
			{
				num = dimension2;
			}
			bool flag = false;
			if (this.DimensionLimit <= num)
			{
				num = this.DimensionLimit;
				flag = true;
			}
			if (!flag)
			{
				if (dimension < dimension2)
				{
					return -1;
				}
				if (dimension > dimension2)
				{
					return 1;
				}
			}
			int num2 = 0;
			while (num2 < count && num2 < count2)
			{
				int num3 = this.CompareCoordinate(s1, s2, num2, num);
				if (num3 != 0)
				{
					return num3;
				}
				num2++;
			}
			if (num2 < count)
			{
				return 1;
			}
			if (num2 < count2)
			{
				return -1;
			}
			return 0;
		}

		protected int DimensionLimit;
	}
}
